package edu.pku.sei.modeler.uml.commands.timing;

import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.commands.Command;

import edu.pku.sei.modeler.exceptions.FactoryNotFoundException;
import edu.pku.sei.modeler.model.common.ModelRegistry;
import edu.pku.sei.modeler.model.structure.MetaBendPoint;
import edu.pku.sei.modeler.model.structure.MetaLink;
import edu.pku.sei.modeler.model.structure.StructureFactory;

public class TimeLineMoveBendPointCommand extends Command {
	private MetaLink link;
	private int index;
	private MetaBendPoint oldBendpoint, newBendpoint;
	private Point right,left;
		
	public TimeLineMoveBendPointCommand(MetaLink link, Point location, int index, Point left, Point right) {
		super("Move Bendpoint");
		this.link = link;
		this.index = index;
		if (index == 0)
			this.left = left;
		else this.left = ((MetaBendPoint)link.getBendPoints().get(index - 1)).getLocation();
		if (index == link.getBendPoints().size() - 1)
			this.right = right;
		else 
			this.right = ((MetaBendPoint)link.getBendPoints().get(index + 1)).getLocation();
		StructureFactory sFactory;
		try {
			sFactory = (StructureFactory)ModelRegistry.getRegistry().getStructureFactory(link.getModelElement().getModel());
			newBendpoint = sFactory.createMetaBendPoint();
			newBendpoint.x = location.x;
			newBendpoint.y = location.y;
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FactoryNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		oldBendpoint = (MetaBendPoint)link.getBendPoints().get(index);
	}

	public boolean canExecute() {
		return link != null && index >= 0 && newBendpoint != null && oldBendpoint != null;
	}
		
	public void execute() {
		if (newBendpoint.x < left.x)
			newBendpoint.x = left.x;
		else if (newBendpoint.x > right.x)
			newBendpoint.x = right.x;
		newBendpoint.y = oldBendpoint.y;
		link.getBendPoints().set(index, newBendpoint);
	}

	public void undo() {
		link.getBendPoints().set(index, oldBendpoint);
	}
}
